import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_magic_planet/common/constant.dart';
import 'package:flutter_magic_planet/common/http/api_video_bljiex.dart';
import 'package:flutter_magic_planet/common/http/api_video_pingcc.dart';
import 'package:flutter_magic_planet/component/icon_button.dart';
import 'package:flutter_magic_planet/model/video.dart';
import 'package:flutter_magic_planet/model/video_chapter.dart';
import 'package:get/get.dart';

import 'video_player_logic.dart';
import 'widget/custom_fijkplayer.dart';

class VideoPlayerPage extends StatefulWidget {
  final Video video;
  final String? sourceId;

  const VideoPlayerPage({Key? key, required this.video, this.sourceId})
      : super(key: key);
  @override
  _VideoPlayerPageState createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  final VideoPlayerLogic logic = Get.put(VideoPlayerLogic());
  double playerHeight = 260;
  List<VideoChapter> chapters = [];

  @override
  void initState() {
    super.initState();
    initVideoChapters(videoId: widget.video.videoId, sourceId: widget.sourceId);
    print('initVideoChapters: ${widget.video.videoId}');
  }

  /// 初始化播放
  initVideoChapters({videoId, String? sourceId}) async {
    switch (sourceId) {
      case APIVideoPingcc.ID:
        chapters = await APIVideoPingcc.getVideoChapters(id: videoId);
        break;
      case APIVideoBljiex.ID:
        chapters = await APIVideoBljiex.getVideoChapters(id: videoId);
    }
    setState(() {});
    // 设置播放地址
    await logic.player
        .setDataSource(chapters[0].chapterUrl ?? '', autoPlay: true);
    // 定位到上次播放进度
    await logic.seekToCachedPosition(
        videoId: widget.video.videoId,
        sourceId: widget.sourceId,
        activeChapterId: 0);
  }

  // 钩子函数，用于更新状态
  void onChangeVideo(int curTabIdx, int curActiveIdx) {
    logic.setActiveChapterId(curActiveIdx);
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      child: Stack(
        children: [
          Container(
            padding: EdgeInsets.only(top: topSafeHeight),
            color: Colors.black,
            child: FijkView(
              height: playerHeight,
              color: Colors.black,
              fit: FijkFit.ar16_9,
              fsFit: FijkFit.ar16_9,
              player: logic.player,
              panelBuilder: (
                FijkPlayer player,
                FijkData data,
                BuildContext context,
                Size viewSize,
                Rect texturePos,
              ) {
                /// 使用自定义的布局
                return CustomFijkPanel(
                  player: player,
                  viewSize: viewSize,
                  texturePos: texturePos,
                  pageContent: context,
                  // 标题 当前页面顶部的标题部分
                  playerTitle: widget.video.title ?? '',
                  // 当前视频改变钩子
                  onChangeVideo: onChangeVideo,
                  // 当前视频源tabIndex
                  curTabIdx: 0,
                  // 当前视频源activeIndex
                  curActiveIdx: logic.curActiveIdx.value,
                  // 显示的配置
                  showConfig: logic.v_cfg,
                  // json格式化后的视频数据
                  videoFormat: chapters,
                );
              },
            ),
          ),
          Positioned(
            top: topSafeHeight + playerHeight,
            child: Container(
              alignment: Alignment.centerLeft,
              height: Get.height - topSafeHeight - playerHeight,
              width: Get.width,
              child: MediaQuery.removePadding(
                context: context,
                removeTop: true,
                child: ListView(
                  children: [
                    // _buildDownloadSheet(),
                    _buildInfo(),
                    _buildTabs(
                      onTap: (activeIdx) async {
                        changeCurPlayVideo(activeIdx);
                      },
                    ),
                    SizedBox(height: 22),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
      value: SystemUiOverlayStyle.light,
    );
  }

  @override
  void dispose() {
    Get.delete<VideoPlayerLogic>();
    super.dispose();
  }

  /// 切换播放源
  Future<void> changeCurPlayVideo(int activeIdx) async {
    await logic.player.stop();
    await logic.player.reset();
    logic.stopSavePlayerCurrentPosition();
    print(
        'after reset && currentPos = ${logic.player.currentPos.inMilliseconds}');
    String curTabActiveUrl = chapters[activeIdx].chapterUrl ?? '';
    await logic.player.setDataSource(
      curTabActiveUrl,
      autoPlay: true,
    );
    logic.setActiveChapterId(activeIdx);
    await logic.seekToCachedPosition(
      videoId: widget.video.videoId,
      sourceId: widget.sourceId,
      activeChapterId: activeIdx,
    );
  }

  /// 视频信息
  _buildInfo() {
    return Container(
      padding:
          EdgeInsets.fromLTRB(paddingHorizontal, 16, paddingHorizontal, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.video.title ?? '未知',
            style: TextStyle(fontWeight: FontWeight.w600, fontSize: 17),
          ),
          Text(
            '${widget.video.videoType} / ${widget.video.descs}',
            style: TextStyle(
              fontWeight: FontWeight.w300,
              color: Colors.black54,
              fontSize: 12,
            ),
          ),
          SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              IconTextButton(
                onPressed: () {},
                iconSize: 18,
                text: Text(
                  '收藏',
                  style: TextStyle(fontSize: 12),
                ),
                icon: Icon(Icons.star_outline),
              ),
              SizedBox(width: 10),
              IconTextButton(
                onPressed: () {
                  Get.bottomSheet(_buildDownloadSheet(), elevation: 0);
                },
                iconSize: 18,
                text: Text(
                  '缓存',
                  style: TextStyle(fontSize: 12),
                ),
                icon: Icon(Icons.cloud_download_outlined),
              ),
              SizedBox(width: 10),
              IconTextButton(
                onPressed: () {},
                iconSize: 18,
                text: Text(
                  '分享',
                  style: TextStyle(fontSize: 12),
                ),
                icon: Icon(Icons.share_outlined),
              ),
              SizedBox(width: 10),
            ],
          ),
        ],
      ),
    );
  }

  /// 剧集按钮列表
  _buildTabs({required Function onTap}) {
    return Container(
      child: GridView.builder(
        shrinkWrap: true,
        itemCount: chapters.length,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.symmetric(horizontal: 16),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          childAspectRatio: 2,
        ),
        itemBuilder: (context, activeIdx) {
          return GestureDetector(
            onTap: () {
              onTap(activeIdx);
            },
            child: Obx(
              () => Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: activeIdx == logic.curActiveIdx.value
                      ? primaryColor
                      : Color(0xffeeeeee),
                ),
                child: Text(
                  chapters[activeIdx].title ?? '未知',
                  style: TextStyle(
                    color: Colors.black,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  /// 下载弹窗
  _buildDownloadSheet() {
    double height = 360;
    return Container(
      color: Colors.white,
      height: height,
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(
                horizontal: paddingHorizontal + 4, vertical: 0),
            alignment: Alignment.centerLeft,
            height: 44,
            child: Text(
              '离线缓存',
              style: TextStyle(fontSize: 20),
            ),
          ),
          Container(
            width: Get.width,
            height: height - 44 - 64,
            padding: EdgeInsets.only(bottom: 8),
            child: SingleChildScrollView(
              child: _buildTabs(
                onTap: (index) {
                  //
                },
              ),
            ),
          ),
          Container(
            height: 64,
            color: Colors.yellow,
            child: GridView.count(
              shrinkWrap: true,
              crossAxisCount: 2,
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(vertical: 0),
              childAspectRatio: 3,
              children: [
                GestureDetector(
                  onTap: () {
                    //
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      '缓存全部',
                      style: TextStyle(color: Colors.white),
                    ),
                    color: Colors.black,
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    //
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text('查看缓存'),
                    color: primaryColor,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}
